/**
 * 
 */
package com.tc.dispatch.web.schedule.dispatch;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsalgorithm.spec.compare;
import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsalgorithm.spec.specConst;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.rwservice.ejb.RWServiceLocal;
import com.tc.dispatch.rwservice.exception.RWException;
import com.tc.dispatch.rwservice.model.ERPWarehouse;
import com.tc.dispatch.web.rwservice.rwHelper;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.YZComparator;

/**
 * @author cajeep
 *
 */
public class DispatchIndex extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DispatchIndex() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		RWServiceLocal rws = rwHelper.getRWServiceLocal();
		HttpSession sess = request.getSession();
		if(action.equals("list"))
		{
			String start=request.getParameter("start");
	        if(start==null)
	        	start="0";
	        String limit=request.getParameter("limit");
	        if(limit==null)
	        	limit="10";
	        try{
		        
	        	List ret=rws.findERPTaskByPages(Integer.parseInt(start), Integer.parseInt(limit));
	        	System.out.println("size:"+ret.size());
	        	JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				String whereStr=" ppedit=0 and productid is not null and productid not like '%-%'";
				json.put("totalProperty", new Integer(rws.getERPTaskTotalNum(whereStr)));
				
				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
	        }
	        catch(Exception e)
	        {
	        	
	        	System.out.println("list error:"+e.getMessage());
	        	response.getWriter().print("{success:false}");
	        }
			
		}
		else if(action.equals("warehouse"))
		{
			
			String type=request.getParameter("type");
			if(type==null)
				{
					type=(String)sess.getAttribute("type");
				}
			else
			{
				sess.setAttribute("type", type);
			}
			String ssign=request.getParameter("ssign");
			if(ssign==null)
				ssign="";
			String spec=request.getParameter("spec");
			if(spec==null)
				spec="";   
			String zhenpian=request.getParameter("zhenpian");
			if(zhenpian==null)
				zhenpian="0";
			String start=request.getParameter("start");
	        if(start==null)
	        	start="0";
	        String limit=request.getParameter("limit");
	        if(limit==null)
	        	limit="10";
	        String isNew=request.getParameter("isNew");
	        if(isNew==null)
	        	isNew="false";
			try{
			if(type.equals("chengpin"))
			{
				List ret;
				if(isNew.equals("true"))
				{
				 String whereStr=" WHERE spec ='" + spec + "' and ssign='"+ssign+"'  and zhenpian >" + zhenpian+" and (prdttype='d' )";
				 ret=rws.findERPWH(whereStr);
				 sess.setAttribute("chengpin", ret);
				}
				else
					ret=(List)sess.getAttribute("chengpin");
				 JSONObject json = new JSONObject();
					JsonConfig cfg = new JsonConfig();
					cfg.registerJsonValueProcessor(java.util.Date.class,
							new DateJsonValueProcessor());
					cfg.registerJsonValueProcessor(java.sql.Date.class,
							new DateJsonValueProcessor());
					List subList;
					if((Integer.parseInt(start)+Integer.parseInt(limit))>ret.size())
					{
						subList=ret.subList(Integer.parseInt(start), ret.size());
					}
					else
						subList=ret.subList(Integer.parseInt(start), Integer.parseInt(start)+Integer.parseInt(limit));

					json.put("totalProperty", new Integer(ret.size()));
					
					JSONArray arr = JSONArray.fromObject(subList.toArray(), cfg);
					json.put("root", arr);
					
					response.getWriter().print(json);
			}
			else if(type.equals("bopian"))
			{
				List ret;
				if(isNew.equals("true"))
				{
				 String whereStr=" WHERE spec ='" + spec + "' and ssign='"+ssign+"'  and zhenpian >" + zhenpian+" and (prdttype='c' )";
				 ret=rws.findERPWH(whereStr);
				 sess.setAttribute("bopian", ret);
				}
				else
					ret=(List)sess.getAttribute("bopian");
				 JSONObject json = new JSONObject();
					JsonConfig cfg = new JsonConfig();
					cfg.registerJsonValueProcessor(java.util.Date.class,
							new DateJsonValueProcessor());
					cfg.registerJsonValueProcessor(java.sql.Date.class,
							new DateJsonValueProcessor());
					List subList;
					if((Integer.parseInt(start)+Integer.parseInt(limit))>ret.size())
					{
						subList=ret.subList(Integer.parseInt(start), ret.size());
					}
					else
						subList=ret.subList(Integer.parseInt(start), Integer.parseInt(start)+Integer.parseInt(limit));

					json.put("totalProperty", new Integer(ret.size()));
					
					JSONArray arr = JSONArray.fromObject(subList.toArray(), cfg);
					json.put("root", arr);
					
					response.getWriter().print(json);
			}
			else if(type.equals("yuanzhu"))
			{
				List ret;
				if(isNew.equals("true"))
				{
					String specStr="";
					if(parse.parseSpec(spec).sort().equals(specConst.YuanZhu))
					{
						specStr=" spec like '$%*%'";
					}
					else if(parse.parseSpec(spec).sort().equals(specConst.TaoKong))
					{
						specStr=" spec like '$%*%'";
					}
					else
					{
						specStr=" spec like '%*%*%'";
					}
					System.out.println("start");
				 String whereStr=" WHERE "+specStr+" and ssign='"+ssign+"'  and zhenpian >" + zhenpian+" and (prdttype='a' or prdttype='b' )";
				 List newList=rws.findERPWH(whereStr);
				// System.out.println("list.size():"+newList.size());
				 Iterator it=newList.iterator();
				 String temp;
			
				 ERPWarehouse erp;
				 ret=new ArrayList();
				 
				 while(it.hasNext())
				 {
					 erp=(ERPWarehouse)it.next();
					 temp=erp.getSpec();
					 if(compare.compareSpec(temp,spec)==1)
						 {
						 //System.out.println("add..");
						 	ret.add(erp);
						 }			 
				 }
				 newList.clear();
				 System.out.println("ret.size():"+ret.size());
				 YZComparator yzc=new YZComparator();
				 Collections.sort(ret,yzc);
				 
				 sess.setAttribute("yuanzhu", ret);
				}
				else
					ret=(List)sess.getAttribute("yuanzhu");
				 JSONObject json = new JSONObject();
					JsonConfig cfg = new JsonConfig();
					cfg.registerJsonValueProcessor(java.util.Date.class,
							new DateJsonValueProcessor());
					cfg.registerJsonValueProcessor(java.sql.Date.class,
							new DateJsonValueProcessor());
					List subList;
					if((Integer.parseInt(start)+Integer.parseInt(limit))>ret.size())
					{
						subList=ret.subList(Integer.parseInt(start), ret.size());
					}
					else
						subList=ret.subList(Integer.parseInt(start), Integer.parseInt(start)+Integer.parseInt(limit));
					
					json.put("totalProperty", new Integer(ret.size()));
					
					JSONArray arr = JSONArray.fromObject(subList.toArray(), cfg);
					json.put("root", arr);
					
					response.getWriter().print(json);
			}
			
			else
			{
				
			}
			}
			catch(RWException e)
			{
				System.out.println("warehouse:"+e.getMessage());
				
			}
			
		}else if(action.equals("jump"))
		{
			String plannum=request.getParameter("plannum");
			String ssign=request.getParameter("ssign");
			String plate=request.getParameter("plate");
			String spec=request.getParameter("spec");
			String zhenpian=request.getParameter("ctrlqty");
			System.out.println("zhenpian:"+zhenpian);
			sess.setAttribute("plannum", plannum);
			sess.setAttribute("ssign", ssign);
			sess.setAttribute("plate", plate);
			sess.setAttribute("spec", spec);
			sess.setAttribute("zhenpian", zhenpian);
		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
